#!/usr/bin/env python
#coding:utf-8

class Wrapper(object):
    def __init__(self,flag,errorDict,formInstance):
        self.Flag = flag
        self.ErrorDict = errorDict
        self.FormInstance = formInstance
        

class FormBinder(object):
    
    @staticmethod
    def FormBind(*formClses):
        def wrapper(func):
            def result(context, *args, **kwargs):
                FormBinder.ExecFormBind(context,formClses)  
                func(context, *args, **kwargs)
            return result
        return wrapper
    
    @staticmethod
    def ExecFormBind(context,formClses):
        context.FomrsInstance = {}
        for formCls in formClses:
            clsName = str(formCls)
            formObj = formCls()
            errorDict = {}
            flag = True
            try:
                formFields = formCls.Meta.Fields
            except Exception,e:
                formFields = formObj.__dict__.keys()
                
            for fieldName in formFields:
                htmlFieldName = "%s.%s" %(clsName,fieldName,)
                
                htmlValue = context.get_argument(htmlFieldName,'')
                
                fieldInstance = formObj.__dict__[fieldName]
                try:
                    result = fieldInstance.Value(htmlValue)
                except Exception,e:
                    tip = "%s%s" %(fieldInstance.Display,e.message,)
                    errorDict[fieldName] = tip
                    flag = False
            wrapper = Wrapper(flag,errorDict,formObj)        
            context.FomrsInstance[clsName] = wrapper
                
            
